package trlygjj.tanruiliyigenjinjin.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import trlygjj.tanruiliyigenjinjin.domain.Permission;
import trlygjj.tanruiliyigenjinjin.domain.SystemMenu;

import java.util.Iterator;
import java.util.List;

/**
 * Created by user on 2018/7/13.
 */
public class SystemMenuUtil {

    public static final String MENU_IN_SESSION = "menu_in_session";

    //过滤掉没有子菜单的根菜单!!!
    public static void filterMenus(List<SystemMenu> menus) {
        filterPermissionMenus(menus);
        if(menus != null) {
            Iterator<SystemMenu> iterator = menus.iterator();
            while (iterator.hasNext()) {
                SystemMenu menu = iterator.next();
                if (menu.getChildren() == null || menu.getChildren().size() == 0) {
                    iterator.remove();
                }
            }
        }
    }
    private static void filterPermissionMenus(List<SystemMenu> menus){
        if (menus != null && menus.size() != 0) {
            Subject subject = SecurityUtils.getSubject();

            Iterator<SystemMenu> iterator = menus.iterator();
            while (iterator.hasNext()) {
                SystemMenu menu = iterator.next();
                Permission permission = menu.getPermission();
                if (permission != null) {
                    if (!subject.isPermitted(permission.getResource())) {
                        iterator.remove();
                    }
                }
                //继续遍历删除子菜单
                if (menu.getChildren() != null && menu.getChildren().size() != 0) {
                    filterPermissionMenus(menu.getChildren());
                }
            }
        }
    }
}
